package com.dsl.dslsuzhou.engine;

/**
 * 时间粒度枚举
 */
public enum Granularity {
    
    HOUR("hour", "DATE_FORMAT(f.%s, '%%Y-%%m-%%d %%H:00:00')"),
    DAY("day", "DATE(f.%s)"),
    MONTH("month", "DATE_FORMAT(f.%s, '%%Y-%%m-01')");
    
    private final String code;
    private final String bucketExprTemplate;
    
    Granularity(String code, String bucketExprTemplate) {
        this.code = code;
        this.bucketExprTemplate = bucketExprTemplate;
    }
    
    public String getCode() {
        return code;
    }
    
    /**
     * 获取bucket表达式
     * @param timeField 时间字段名
     * @return bucket表达式
     */
    public String getBucketExpr(String timeField) {
        return String.format(bucketExprTemplate, timeField);
    }
    
    /**
     * 根据代码获取粒度
     */
    public static Granularity fromCode(String code) {
        for (Granularity g : values()) {
            if (g.code.equals(code)) {
                return g;
            }
        }
        throw new IllegalArgumentException("Unsupported granularity: " + code);
    }
}
